""" DigitalICS: mobile data collection tool to complete surveys with integrated multimedia

    Copyright (C) 2009. Yael Schwartzman  

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>
    
    Contact information: Yael Schwartzman -  yaelsf@gmail.com
    """
import os.path as path
import cerealizer.cerealizer as cerealizer
from api.fexplorer import FExplorer

class Pickler:
    
    def __init__(self,pc = False):
        self.fexplorer = FExplorer(pc = pc)
        self.pickle_file = self.fexplorer.get_organization_pickle_file()
        if not path.exists(self.pickle_file):
            self.create_pickle_file()
        self.pickle_obj = self.load()
        
    def create_pickle_file(self):
        organization_file = open(self.fexplorer.get_organization_data_file(),'r')
        cd_contents = organization_file.read()
        cd_contents = cd_contents.replace("\n","")
        cd_list = cd_contents.split("%%")
        organization_file.close()
        #cols
        CLAVE_ORG = 0
        RECOMMENDATION = 1
        COMMUNITY = 2
        NAME = 3
        c_dict = {}
        for line in cd_list:
            items = line.split(';')
            if len(items) == 4:
                #if not c_dict.has_key(items[COMMUNITY]):
                #    c_dict[items[COMMUNITY]] = {}
                #community_dict = c_dict[items[COMMUNITY]]
                if not c_dict.has_key(items[CLAVE_ORG]):
                    c_dict[items[CLAVE_ORG]] = {'name': items[NAME],
                                                    'recommendations': items[RECOMMENDATION]}
        
        self.dump(c_dict)
    
    def dump(self,obj):
        p_file = open(self.pickle_file,'wb')
        cerealizer.dump(obj,p_file)
        p_file.close()
    
    def load(self):
        p_file = open(self.pickle_file,'rb')
        obj = cerealizer.load(p_file)
        p_file.close()
        
        return obj 

    #def get_communities(self):
    #    return self.pickle_obj.keys()
        
    def get_producer_codes(self):
        return self.pickle_obj.keys()
     
    def get_producer_id(self,prod_path):
        parts =[]
        length = [3,4,3,3]
        length_count = 0
        for i in range(len(length)):
            prod_path,item = path.split(prod_path)
            zeros = length[i] - len(item)
            for j in range(zeros):
                item = "0" + item
            parts.insert(0,item)
            

        id = "E" + "".join(parts)
        return id

    def get_recommendation(self,community=None,municipio = None, localidad = None, producer= None):
        
        code = self.get_producer_id("%s/%s/%s/%s" % (community,municipio,localidad,producer))
        if self.pickle_obj.has_key(code):
            return "%s: %s" % (self.pickle_obj[code]['name'],self.pickle_obj[code]['recommendations'])
        else:
            return ""
#            comm = self.pickle_obj[community]
#            for k,v in comm.iteritems():
#                if v['name'] == producer:
#                    return comm[k]['recommendations']
        
    def get_producer_names(self,community):
        comm = self.pickle_obj[community]
        return [comm[code]['name'] for code in comm.keys()]
    
    def get_producer_code(self,community,producer_name):
        comm = self.pickle_obj[community]
        for k,v in comm.iteritems():
            if v['name'] == producer_name:
                return k
    
if __name__=="__main__": 
    p = Pickler()
    d = p.load()
    

    producers = p.get_producer_codes()
    for prod in producers:
        rec = p.get_recommendation(prod)
